<?php
session_start();
include('../includes/config.php');
include('../includes/functions.php');

// 检查用户是否已登录，且是患者角色
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'patient') {
    header("Location: ../login.php");
    exit();
}

// 获取患者ID
$patient_id = $_SESSION['user_id'];

// 获取患者信息
$stmt = $conn->prepare("SELECT u.*, p.* FROM users u JOIN patients p ON u.id = p.user_id WHERE u.id = ?");
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$patient_info = $stmt->get_result()->fetch_assoc();
$stmt->close();

// 设置默认值
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';
$date_filter = isset($_GET['date']) ? $_GET['date'] : 'all';
$sort_by = isset($_GET['sort']) ? $_GET['sort'] : 'date_desc';

// 构建WHERE子句
$where_clause = "WHERE a.patient_id = ?";
$params = array($patient_info['id']);
$types = "i";

// 根据状态筛选
if ($status_filter != 'all') {
    $where_clause .= " AND a.status = ?";
    $params[] = $status_filter;
    $types .= "s";
}

// 根据日期筛选
if ($date_filter != 'all') {
    $today = date('Y-m-d');
    
    if ($date_filter == 'upcoming') {
        $where_clause .= " AND a.appointment_date >= ?";
        $params[] = $today;
        $types .= "s";
    } elseif ($date_filter == 'past') {
        $where_clause .= " AND a.appointment_date < ?";
        $params[] = $today;
        $types .= "s";
    } elseif ($date_filter == 'today') {
        $where_clause .= " AND a.appointment_date = ?";
        $params[] = $today;
        $types .= "s";
    } elseif ($date_filter == 'week') {
        $week_later = date('Y-m-d', strtotime('+7 days'));
        $where_clause .= " AND a.appointment_date BETWEEN ? AND ?";
        $params[] = $today;
        $params[] = $week_later;
        $types .= "ss";
    }
}

// 构建ORDER BY子句
$order_clause = "";
switch ($sort_by) {
    case 'date_asc':
        $order_clause = "ORDER BY a.appointment_date ASC, a.appointment_time ASC";
        break;
    case 'date_desc':
        $order_clause = "ORDER BY a.appointment_date DESC, a.appointment_time DESC";
        break;
    case 'created_asc':
        $order_clause = "ORDER BY a.created_at ASC";
        break;
    case 'created_desc':
        $order_clause = "ORDER BY a.created_at DESC";
        break;
    default:
        $order_clause = "ORDER BY a.appointment_date DESC, a.appointment_time DESC";
}

// 统计符合条件的预约总数
$count_query = "SELECT COUNT(*) as total FROM appointments a $where_clause";
$stmt = $conn->prepare($count_query);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$total_appointments = $stmt->get_result()->fetch_assoc()['total'];
$stmt->close();

// 分页设置
$appointments_per_page = 10;
$total_pages = ceil($total_appointments / $appointments_per_page);
$current_page = isset($_GET['page']) ? max(1, min($total_pages, intval($_GET['page']))) : 1;
$offset = ($current_page - 1) * $appointments_per_page;

// 获取预约数据
$query = "
    SELECT a.*, d.title, u.name as doctor_name, dp.name as department_name 
    FROM appointments a 
    JOIN doctors d ON a.doctor_id = d.id 
    JOIN users u ON d.user_id = u.id 
    JOIN departments dp ON a.department_id = dp.id 
    $where_clause 
    $order_clause 
    LIMIT ?, ?
";

$stmt = $conn->prepare($query);
$params[] = $offset;
$params[] = $appointments_per_page;
$types .= "ii";
$stmt->bind_param($types, ...$params);
$stmt->execute();
$appointments = $stmt->get_result();
$stmt->close();

// 获取预约状态统计
$status_stats = array(
    'all' => $total_appointments,
    'pending' => 0,
    'confirmed' => 0,
    'completed' => 0,
    'cancelled' => 0
);

$stmt = $conn->prepare("
    SELECT status, COUNT(*) as count 
    FROM appointments 
    WHERE patient_id = ? 
    GROUP BY status
");
$stmt->bind_param("i", $patient_info['id']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $status_stats[$row['status']] = $row['count'];
}
$stmt->close();

// 获取日期统计
$date_stats = array(
    'all' => $total_appointments,
    'upcoming' => 0,
    'past' => 0,
    'today' => 0,
    'week' => 0
);

$today = date('Y-m-d');
$week_later = date('Y-m-d', strtotime('+7 days'));

// 今天的预约
$stmt = $conn->prepare("
    SELECT COUNT(*) as count 
    FROM appointments 
    WHERE patient_id = ? AND appointment_date = ?
");
$stmt->bind_param("is", $patient_info['id'], $today);
$stmt->execute();
$date_stats['today'] = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

// 未来的预约
$stmt = $conn->prepare("
    SELECT COUNT(*) as count 
    FROM appointments 
    WHERE patient_id = ? AND appointment_date >= ?
");
$stmt->bind_param("is", $patient_info['id'], $today);
$stmt->execute();
$date_stats['upcoming'] = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

// 过去的预约
$stmt = $conn->prepare("
    SELECT COUNT(*) as count 
    FROM appointments 
    WHERE patient_id = ? AND appointment_date < ?
");
$stmt->bind_param("is", $patient_info['id'], $today);
$stmt->execute();
$date_stats['past'] = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

// 一周内的预约
$stmt = $conn->prepare("
    SELECT COUNT(*) as count 
    FROM appointments 
    WHERE patient_id = ? AND appointment_date BETWEEN ? AND ?
");
$stmt->bind_param("iss", $patient_info['id'], $today, $week_later);
$stmt->execute();
$date_stats['week'] = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

// 构建分页链接的基础URL
$base_url = "appointments.php?";
$query_params = $_GET;
unset($query_params['page']); // 移除page参数，以便构建新的分页链接
foreach ($query_params as $key => $value) {
    $base_url .= $key . '=' . $value . '&';
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的预约 - 医院信息系统</title>
    <link rel="stylesheet" href="/assets\css/bootstrap_69c9e605.min.css">
    <link rel="stylesheet" href="/assets\css/style.css">
    <link rel="stylesheet" href="/assets\css/all_de197510.min.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <img src="../assets/images/patient-avatar.png" alt="患者头像" class="img-fluid rounded-circle mx-auto d-block" style="width: 80px;">
                        <h5 class="mt-2"><?php echo htmlspecialchars($patient_info['name']); ?></h5>
                        <p class="text-muted">患者ID: <?php echo htmlspecialchars($patient_info['id']); ?></p>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="index.php">
                                <i class="fas fa-home"></i> 个人中心
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="appointments.php">
                                <i class="fas fa-calendar-check"></i> 我的预约
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="book_appointment.php">
                                <i class="fas fa-plus-circle"></i> 预约挂号
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="medical_records.php">
                                <i class="fas fa-notes-medical"></i> 病历记录
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="prescriptions.php">
                                <i class="fas fa-prescription"></i> 处方信息
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="bills.php">
                                <i class="fas fa-file-invoice-dollar"></i> 账单管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="profile.php">
                                <i class="fas fa-user"></i> 个人信息
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="../logout.php">
                                <i class="fas fa-sign-out-alt"></i> 退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">我的预约</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="book_appointment.php" class="btn btn-sm btn-primary">
                            <i class="fas fa-plus-circle"></i> 新预约
                        </a>
                    </div>
                </div>

                <!-- 筛选与统计 -->
                <div class="row mb-4">
                    <div class="col-md-12">
                        <div class="card shadow-sm">
                            <div class="card-body">
                                <div class="row">
                                    <!-- 状态筛选 -->
                                    <div class="col-md-4 mb-3">
                                        <label for="statusFilter" class="form-label"><i class="fas fa-filter"></i> 按状态筛选</label>
                                        <select id="statusFilter" class="form-select" onchange="applyFilter()">
                                            <option value="all" <?php echo $status_filter == 'all' ? 'selected' : ''; ?>>全部 (<?php echo $status_stats['all']; ?>)</option>
                                            <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>待确认 (<?php echo $status_stats['pending']; ?>)</option>
                                            <option value="confirmed" <?php echo $status_filter == 'confirmed' ? 'selected' : ''; ?>>已确认 (<?php echo $status_stats['confirmed']; ?>)</option>
                                            <option value="completed" <?php echo $status_filter == 'completed' ? 'selected' : ''; ?>>已完成 (<?php echo $status_stats['completed']; ?>)</option>
                                            <option value="cancelled" <?php echo $status_filter == 'cancelled' ? 'selected' : ''; ?>>已取消 (<?php echo $status_stats['cancelled']; ?>)</option>
                                        </select>
                                    </div>
                                    
                                    <!-- 日期筛选 -->
                                    <div class="col-md-4 mb-3">
                                        <label for="dateFilter" class="form-label"><i class="fas fa-calendar"></i> 按日期筛选</label>
                                        <select id="dateFilter" class="form-select" onchange="applyFilter()">
                                            <option value="all" <?php echo $date_filter == 'all' ? 'selected' : ''; ?>>全部时间 (<?php echo $date_stats['all']; ?>)</option>
                                            <option value="today" <?php echo $date_filter == 'today' ? 'selected' : ''; ?>>今天 (<?php echo $date_stats['today']; ?>)</option>
                                            <option value="week" <?php echo $date_filter == 'week' ? 'selected' : ''; ?>>未来7天 (<?php echo $date_stats['week']; ?>)</option>
                                            <option value="upcoming" <?php echo $date_filter == 'upcoming' ? 'selected' : ''; ?>>所有未来预约 (<?php echo $date_stats['upcoming']; ?>)</option>
                                            <option value="past" <?php echo $date_filter == 'past' ? 'selected' : ''; ?>>历史预约 (<?php echo $date_stats['past']; ?>)</option>
                                        </select>
                                    </div>
                                    
                                    <!-- 排序 -->
                                    <div class="col-md-4 mb-3">
                                        <label for="sortBy" class="form-label"><i class="fas fa-sort"></i> 排序方式</label>
                                        <select id="sortBy" class="form-select" onchange="applyFilter()">
                                            <option value="date_desc" <?php echo $sort_by == 'date_desc' ? 'selected' : ''; ?>>预约日期（从新到旧）</option>
                                            <option value="date_asc" <?php echo $sort_by == 'date_asc' ? 'selected' : ''; ?>>预约日期（从旧到新）</option>
                                            <option value="created_desc" <?php echo $sort_by == 'created_desc' ? 'selected' : ''; ?>>创建时间（从新到旧）</option>
                                            <option value="created_asc" <?php echo $sort_by == 'created_asc' ? 'selected' : ''; ?>>创建时间（从旧到新）</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 预约列表 -->
                <div class="card shadow-sm mb-4">
                    <div class="card-header py-3">
                        <h5 class="mb-0"><i class="fas fa-list"></i> 预约列表</h5>
                    </div>
                    <div class="card-body">
                        <?php if ($appointments->num_rows > 0): ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>预约编号</th>
                                            <th>日期 / 时间</th>
                                            <th>科室</th>
                                            <th>医生</th>
                                            <th>状态</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while ($appointment = $appointments->fetch_assoc()): ?>
                                        <tr>
                                            <td>#<?php echo $appointment['id']; ?></td>
                                            <td>
                                                <span class="d-block"><?php echo date('Y-m-d', strtotime($appointment['appointment_date'])); ?></span>
                                                <small class="text-muted"><?php echo $appointment['appointment_time']; ?></small>
                                            </td>
                                            <td><?php echo htmlspecialchars($appointment['department_name']); ?></td>
                                            <td>
                                                <span class="d-block"><?php echo htmlspecialchars($appointment['doctor_name']); ?></span>
                                                <small class="text-muted"><?php echo htmlspecialchars($appointment['title']); ?></small>
                                            </td>
                                            <td>
                                                <?php
                                                switch ($appointment['status']) {
                                                    case 'pending':
                                                        echo '<span class="badge bg-warning">待确认</span>';
                                                        break;
                                                    case 'confirmed':
                                                        echo '<span class="badge bg-info">已确认</span>';
                                                        break;
                                                    case 'completed':
                                                        echo '<span class="badge bg-success">已完成</span>';
                                                        break;
                                                    case 'cancelled':
                                                        echo '<span class="badge bg-danger">已取消</span>';
                                                        break;
                                                    default:
                                                        echo '<span class="badge bg-secondary">未知</span>';
                                                }
                                                ?>
                                            </td>
                                            <td><?php echo date('Y-m-d', strtotime($appointment['created_at'])); ?></td>
                                            <td>
                                                <a href="appointment_details.php?id=<?php echo $appointment['id']; ?>" class="btn btn-sm btn-outline-primary" title="查看详情">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                <?php if ($appointment['status'] == 'pending' || $appointment['status'] == 'confirmed'): ?>
                                                <a href="appointment_details.php?id=<?php echo $appointment['id']; ?>&action=cancel" class="btn btn-sm btn-outline-danger" title="取消预约" onclick="return confirm('确定要取消此预约吗？');">
                                                    <i class="fas fa-times"></i>
                                                </a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- 分页 -->
                            <?php if ($total_pages > 1): ?>
                            <nav aria-label="Page navigation">
                                <ul class="pagination justify-content-center mt-4">
                                    <li class="page-item <?php echo ($current_page <= 1) ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="<?php echo $base_url; ?>page=<?php echo ($current_page - 1); ?>" aria-label="Previous">
                                            <span aria-hidden="true">&laquo;</span>
                                        </a>
                                    </li>
                                    
                                    <?php
                                    $start_page = max(1, $current_page - 2);
                                    $end_page = min($total_pages, $current_page + 2);
                                    
                                    if ($start_page > 1) {
                                        echo '<li class="page-item"><a class="page-link" href="' . $base_url . 'page=1">1</a></li>';
                                        if ($start_page > 2) {
                                            echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                                        }
                                    }
                                    
                                    for ($i = $start_page; $i <= $end_page; $i++) {
                                        echo '<li class="page-item ' . (($i == $current_page) ? 'active' : '') . '"><a class="page-link" href="' . $base_url . 'page=' . $i . '">' . $i . '</a></li>';
                                    }
                                    
                                    if ($end_page < $total_pages) {
                                        if ($end_page < $total_pages - 1) {
                                            echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                                        }
                                        echo '<li class="page-item"><a class="page-link" href="' . $base_url . 'page=' . $total_pages . '">' . $total_pages . '</a></li>';
                                    }
                                    ?>
                                    
                                    <li class="page-item <?php echo ($current_page >= $total_pages) ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="<?php echo $base_url; ?>page=<?php echo ($current_page + 1); ?>" aria-label="Next">
                                            <span aria-hidden="true">&raquo;</span>
                                        </a>
                                    </li>
                                </ul>
                            </nav>
                            <?php endif; ?>
                        <?php else: ?>
                            <div class="text-center py-5">
                                <img src="../assets/images/no-data.svg" alt="无数据" style="width: 150px;" class="mb-3">
                                <h5>未找到预约记录</h5>
                                <p class="text-muted">根据当前筛选条件，未找到任何预约记录</p>
                                <div class="mt-3">
                                    <a href="appointments.php" class="btn btn-outline-secondary me-2">清除筛选条件</a>
                                    <a href="book_appointment.php" class="btn btn-primary">立即预约</a>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 脚本 -->
    <script src="/assets\js/jquery-3.6.0.min.js"></script></script></script>
    <script src="/assets\js/bootstrap.bundle.min.js"></script></script></script>
    <script>
        function applyFilter() {
            const statusFilter = document.getElementById('statusFilter').value;
            const dateFilter = document.getElementById('dateFilter').value;
            const sortBy = document.getElementById('sortBy').value;
            
            let url = 'appointments.php?status=' + statusFilter + '&date=' + dateFilter + '&sort=' + sortBy;
            window.location.href = url;
        }
    </script>
</body>
</html> 